package com.gdteam.kernel.content.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.tapestry5.ioc.annotations.EagerLoad;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.slf4j.Logger;

import com.gdteam.kernel.conf.Environment;
import com.gdteam.kernel.content.ContentEnvironment;
import com.gdteam.kernel.content.ContentIndexationService;
import com.gdteam.kernel.content.IndexManager;
import com.gdteam.kernel.main.ServiceManager;

@EagerLoad
public class DefaultIndexManager implements IndexManager {
    
    private Logger log;
    private ServiceManager manager;
    private boolean started;
    
    private Map<String,ContentIndexationService> idxes = new HashMap<String, ContentIndexationService>();
    
    @Inject @Symbol(ContentEnvironment.CONTENT_ROOT_DIR)
    private String rootDir;
    
    @Inject @Symbol(Environment.GDTEAM_HOME)
    private String homeDir;
    
    public DefaultIndexManager(Logger log, @Inject ServiceManager manager) {
        this.manager = manager;
        manager.registerOperations(this);
        this.log = log;
    }

    public ContentIndexationService createFSIndexService(String idxName, String path) {
        return null;
    }
    
    public ContentIndexationService getIndexationService(String index) {
        return this.idxes.get(index);
    }

    public String getName() {
        return FQN;
    }
    
    
    private void loadLocalIndexationService() {
        
        if (null == this.idxes.get(ContentEnvironment.LOCAL_IDX_NAME)) {
            ContentIndexationService service = new DefaultContentIndexationServiceImpl(this.manager,this.rootDir,this.log,this.homeDir);
            this.idxes.put(ContentEnvironment.LOCAL_IDX_NAME, service);
            service.start();
        }
        
    }

    public void start() {
        if (!started) {
            loadLocalIndexationService();
            this.started = true;
        }
    }

    public void stop() {
        if (started) {
            for (ContentIndexationService service : this.idxes.values()) {
                service.stop();
            }
           this.started = false;
        }
    }

    public boolean isStarted() {
        return this.started;
    }

    
}
